package com.eric.demo.alitest;

import java.math.BigDecimal;
import java.util.Random;

/**
 * @author guangyin.zhang
 * @since 2019/7/17
 * 解题思路：
 * 1. 每个人先随机生成一个随机数，范围在[1, 99*num]
 * 2. 对所有人获得的随机数求和，获取一个count值
 * 3. 每个人按自己的随机rnd/count的比例得到红包值
 * 4. 最后一个人的红包总红包数减去前面人红包
 */
public class RedWallet {

    static double MIN_MONEY = 0.01d;

    public static void main(String[] args){
        double money = 100d;
        int num = 20;
        BigDecimal[] res = distribution(new BigDecimal(money), num);
        for(int i=0; i<num; i++){
            System.out.println(res[i]);
        }
    }


    public static BigDecimal[] distribution(BigDecimal money, int num){
        if(money.doubleValue() < num * MIN_MONEY){
            throw new RuntimeException("金额错误");
        }

        Random random = new Random();
        int allMoney = money.multiply(BigDecimal.valueOf(100)).intValue();

        int count = 0;
        double[] rnds = new double[num];
        BigDecimal[] perWallet = new BigDecimal[num];

        for (int i = 0; i < rnds.length; i++) {
            int r = random.nextInt((num) * 99) + 1;
            count += r;
            rnds[i] = r;
        }

        int assigned = 0;
        for (int i = 0; i < rnds.length; i++) {
            Double x = new Double(rnds[i] / count);
            int wallet = (int) Math.floor(x * allMoney);
            if (wallet == 0) {
                wallet = 1;
            }
            assigned += wallet;

            if (i < rnds.length - 1) {
                perWallet[i] = (new BigDecimal(wallet).divide(new BigDecimal(100)));
            } else {
                perWallet[i] = (new BigDecimal(allMoney - assigned + wallet).divide(new BigDecimal(100)));
            }
        }
        return perWallet;

    }


}
